﻿using System;
using System.IO;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc.Html
{
	public class MvcHtmlTag : IDisposable
	{
		private bool _isDisposed;
		private readonly FormContext _originalFormContext;
		private readonly string _tagName;
		private readonly ViewContext _viewContext;
		private readonly TextWriter _writer;

		public MvcHtmlTag(ViewContext viewContext, string tagName)
		{
			Guard.NotNull(viewContext, "viewContext");
			Guard.NotNullOrEmpty(tagName, "tagName");

			_originalFormContext = viewContext.FormContext;
			_tagName = tagName;
			_viewContext = viewContext;
			_viewContext.FormContext = new FormContext();
			_writer = viewContext.Writer;
		}

		public void Dispose()
		{
			Dispose(true /* disposing */);

			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_isDisposed && disposing)
			{
				_writer.Write("</{0}>", _tagName);

				if (_viewContext != null)
				{
					_viewContext.OutputClientValidation();
					_viewContext.FormContext = _originalFormContext;
				}
			}

			_isDisposed = true;
		}

		public void EndTag()
		{
			Dispose(true /* disposing */);
		}
	}
}